package vip.xiaonuo.invoice.core.handler;

import lombok.extern.slf4j.Slf4j;
import org.springframework.core.annotation.Order;
import org.springframework.validation.BindException;
import org.springframework.web.bind.MethodArgumentNotValidException;
// 添加了Ordered导入
import org.springframework.core.Ordered;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import vip.xiaonuo.common.pojo.CommonResult;
import vip.xiaonuo.invoice.core.exception.InvoiceException;

@Slf4j
@RestControllerAdvice
// 添加最高优先级注解
@Order(Ordered.HIGHEST_PRECEDENCE)
public class DiyGlobalExceptionHandler {

    @ExceptionHandler(value = InvoiceException.class)
    public CommonResult invoiceExceptionHandler(InvoiceException e) {
        log.info("invoice exception！The reason is：{}", e.getMessage(), e);
        // 使用系统通用的CommonResult来返回响应
        return CommonResult.get(e.getErrorCode() != null ? e.getErrorCode() : 499, e.getMessage(), null);
    }

    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public CommonResult methodArgumentNotValidExceptionExceptionHandler(MethodArgumentNotValidException e) {
        StringBuilder errorMsg = new StringBuilder();
        e.getBindingResult().getFieldErrors().forEach(x -> errorMsg.append(x.getField()).append(x.getDefaultMessage()).append(","));
        String message = errorMsg.toString();
        log.info("validation parameters error！The reason is:{}", message);
        return CommonResult.get(400, message.substring(0, message.length() - 1), null);
    }

    @ExceptionHandler(value = BindException.class)
    public CommonResult bindException(BindException e) {
        StringBuilder errorMsg = new StringBuilder();
        e.getBindingResult().getFieldErrors().forEach(x -> errorMsg.append(x.getField()).append(x.getDefaultMessage()).append(","));
        String message = errorMsg.toString();
        log.info("validation parameters error！The reason is:{}", message);
        return CommonResult.get(400, message.substring(0, message.length() - 1), null);
    }

    @ExceptionHandler(value = RuntimeException.class)
    public CommonResult runtimeExceptionHandler(RuntimeException e) {
        log.error("runtime exception！The reason is：{}", e.getMessage(), e);
        // 直接返回异常消息，而不是默认的"服务器异常"
        return CommonResult.get(500, e.getMessage() != null ? e.getMessage() : "服务器异常", null);
    }

    @ExceptionHandler(value = Exception.class)
    public CommonResult exceptionHandler(Exception e) {
        log.error("general exception！The reason is：{}", e.getMessage(), e);
        // 直接返回异常消息，而不是默认的"服务器异常"
        return CommonResult.get(500, "服务器异常", null);
    }
}
